package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodUploadClient vodUploadClient;

    /**
     * @Description 上传文件的时候,需要将上传文件,转存到本地,
     * 再从本地,把本地文件上传到云点播服务
     *
     * 注意点:本地的临时路径,最好不要设置在C盘,比如我一开始设置在桌面,由于桌面这个文件夹被系统设置了只读权限,所以文件创建不成功
     * 建议:将临时路径,设置在系统其他盘符
     */
    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        // 将上传的文件转存到本地
        String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);

        // 构造上传的请求对象
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(tempPath);
        try {
            VodUploadResponse response = vodUploadClient.upload(vodConstantProperties.getRegion(), request);
            Map<String, String> result = new HashMap<>();
            result.put("mediaFileId", response.getFileId());
            result.put("mediaUrl", response.getMediaUrl());
            return result;
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        return null;
    }
}
